<script setup>
import { deleteUser } from "@/api/user";
import { ref } from "vue";
import "@material/web/button/text-button";
import MaterialDialog from "../MaterialDialog.vue";

const props = defineProps(["open", "user"]);
const emit = defineEmits(["close", "done", "error"]);

const deleteDialog = ref(null);

async function onSubmit() {
  if (deleteDialog.value.dialog.returnValue != "delete") {
    return;
  }
  deleteDialog.value.dialog.returnValue = null;
  try {
    await deleteUser(props.user.id);
    emit("done");
  } catch (ex) {
    emit("error", ex.toString());
  }
}
</script>

<template>
  <MaterialDialog ref="deleteDialog" :open="open" @close="onSubmit(); $emit('close')">
    <template #headline>
      删除用户
    </template>

    <template #content>
      <form id="delete-user-dialog" method="dialog">
        <p>确认删除用户 {{ props.user?.username }} 吗？</p>
      </form>
    </template>

    <template #actions>
      <md-text-button type="submit" value="cancel" form="delete-user-dialog" autofocus>取消</md-text-button>
      <md-text-button type="submit" value="delete" form="delete-user-dialog">删除</md-text-button>
    </template>
  </MaterialDialog>
</template>